#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, math

from flask import render_template, request, jsonify
from dbConnection.MysqlConn import Mysql
from app import PAGE_NUM, page_code, upload_files
from . import admin
from app.util import admin_login

reload(sys)
sys.setdefaultencoding('utf8')


# 教师列表
@admin.route('/admin/teacher_list.html')
@admin_login
def teacher_list():
    return render_template('admin/teacher/teacher_list.html')


# 获取数据
@admin.route('/admin/teacher_list_post', methods=['post'])
@admin_login
def teacher_list_post():
    parms = ['cname']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', '1')
    c_num = (int(p) - 1)*PAGE_NUM
    sql = "select * FROM girl_teacher WHERE 1=1"
    sql2 = "select count(*) as con FROM girl_teacher WHERE 1=1"
    if maps['cname']:
        sql += " and uid = '" + maps['cname'] + "' or locate('" + maps['cname'] + "', nickName)>0"
        sql2 += " and uid = '" + maps['cname'] + "' or locate('" + maps['cname'] + "', nickName)>0"
    sql += " order by uid desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    pages = int(math.ceil(cont['con'] / float(PAGE_NUM))) if cont else 0
    route_path = 'get_data'
    html_str = page_code.page_code_html_post(int(p), route_path, pages) if pages > 0 else ''
    if res:
        for d in res:
            d['registerTime'] = str(d['registerTime'])
        data = {
            'status':1,
            'res':res,
            'page':html_str,
            'p':p
        }
    else:
        data = {
            'status':2,
            'page':html_str
        }
    return jsonify(data)


# 修改状态
@admin.route('/admin/update_teacher_post', methods=['post'])
@admin_login
def update_teacher_post():
    uid = request.values.get('uid')
    pid = request.values.get('pid')
    if pid == '1':
        sql = "update girl_teacher set status = 1 WHERE uid = '%s'" % uid
    elif pid == '2':
        sql = "update girl_teacher set status = 0 WHERE uid = '%s'" % uid
    elif pid == '3':
        sql = "delete FROM girl_teacher WHERE uid = '%s'" % uid
    else:
        return jsonify({'status':0})
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 新建教师
@admin.route('/admin/teacher_add.html')
@admin_login
def teacher_add():
    return render_template('admin/teacher/teacher_add.html')


# 新建教师处理
@admin.route('/admin/teacher_add_post', methods=['post'])
@admin_login
def teacher_add_post():
    username = request.values.get('username')
    password = request.values.get('password')
    nickname = request.values.get('nickname')
    phone = request.values.get('phone')
    info = request.values.get('info')
    top = request.files.get('file')
    con = get_teacher_user(username)
    if con:
        return jsonify({'status':2})
    res = insert_teacher(username, password, nickname, phone, info)
    if res > 0:
        top_img = upload_files.upload_teacher_top(res, top)
        update_teacher_top(res, top_img)
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 编辑教师
@admin.route('/admin/teacher_detail.html')
@admin_login
def teacher_detail():
    uid = request.args.get('uid')
    sql = "select * FROM girl_teacher WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    if res:
        if res['header'] and 'http' not in res['header']:
            res['header'] = upload_files.baseUrl + res['header']
    return render_template('admin/teacher/teacher_detail.html', res=res)


# 修改教师资料
@admin.route('/admin/teacher_detail_post', methods=['post'])
@admin_login
def teacher_detail_post():
    uid = request.values.get('uid')
    password = request.values.get('password')
    nickname = request.values.get('nickname')
    phone = request.values.get('phone')
    info = request.values.get('info')
    con = get_teacher_uid(uid)
    if con is None:
        return jsonify({'status':2})
    top = request.files.get('file')
    top_img = upload_files.upload_teacher_top(uid, top)
    sql = "update girl_teacher SET password = '%s', nickName = '%s', info = '%s', phone = '%s'" \
          % (password, nickname, info, phone)
    if top_img:
        sql += ", header = '%s'" % top_img
    sql += " where uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status':1
        }
    else:
        data = {
            'status':0
        }
    return jsonify(data)


# 查询账号是否存在
def get_teacher_user(username):
    sql = "select * FROM girl_teacher WHERE username = '%s'" % username.strip()
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 查询教师是否存在
def get_teacher_uid(uid):
    sql = "select * FROM girl_teacher WHERE uid = '%s'" % uid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 新增教师账号
def insert_teacher(user, password, name, phone, info):
    sql = "insert INTO girl_teacher(username, password, nickName, phone, info, registerTime) VALUES ('%s', '%s', " \
          "'%s', '%s', '%s', now())" % (user.strip(), password, name, phone, info)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 更新教师头像
def update_teacher_top(uid, url):
    sql = "update girl_teacher SET header = '%s' WHERE uid = '%s'" % (url, uid)
    mysql = Mysql()
    mysql.update(sql, None)
    mysql.dispose()